import createHistory from 'history/createHashHistory';
import { message } from 'antd';
import * as Api from './service';

const history = createHistory();

export default {
  namespace: 'root',
  state: {
    drawerStatus: false,
    openKeys: '',
    busniessLst: {},
    menuData: [{
      icon: 'shangjia',
      id: 1,
      name: '首页',
      url: '/main',
      children: [],
    }, {
      icon: 'jiaoyijilu',
      id: 2,
      name: '交易查询',
      url: '/order',
      children: [{
        icon: '',
        id: 3,
        name: '商户交易查询',
        url: '/order/merchant',
      }],
    }],
    // {
    //   icon: 'jiesuanshenpi',
    //   id: 6,
    //   name: '结算管理',
    //   url: '/settlement',
    //   children: [{
    //     icon: '',
    //     id: 7,
    //     name: '商户对账管理',
    //     url: '/settlement/reconciliate',
    //   }],
    // }
  },
  reducers: {
    closeDrawer(state) {
      return { ...state, drawerStatus: false };
    },
    updateMenu(state, { payload: resData }) {
      return { ...state, openKeys: resData };
    },
    updateBusniessLst(state, { payload: resData }) {
      return { ...state, busniessLst: resData };
    },
    openDrawer(state) {
      return { ...state, drawerStatus: true };
    },
  },
  effects: {
    *getBusniessLst({ payload }, { call, put }) {
      const { data } = yield call(Api.getBusniessLst, payload);
      if (data.rspCd == '00000') {
        const temp = {};
        data.data.forEach((item) => {
          temp[item.code] = item;
        });
        yield put({ type: 'updateBusniessLst', payload: temp });
      } else {
        message.error(data.rspInf || '查询失败');
      }
    },
    *loginout({ payload }, { call }) {
      const { data } = yield call(Api.loginout);
      if (data.rspCd == '00000') {
        history.push({
          pathname: '/login',
        });
      } else {
        message.error(data.rspInf || '注销失败');
      }
    },
    *tempJumpPage({ payload }, { put, select }) {
      const pathSnippets = payload.split('/').filter(i => i);
      const selectedMenus = pathSnippets.map((_, index) => {
        return `/${pathSnippets.slice(0, index + 1).join('/')}`;
      });
      yield put({ type: 'updateMenu', payload: selectedMenus[0] });
    },
  },
  // subscriptions: {
  //   setup({ dispatch, history }) {
  //     return history.listen(({ pathname }) => {
  //       dispatch({
  //         type: 'tempJumpPage',
  //         payload: pathname,
  //       });
  //     });
  //   },
  // },
};
